package com.example.demo;

import com.example.vo.User;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import org.apache.commons.io.IOUtils;

import javax.xml.validation.Schema;
import java.io.IOException;

public class GraphQLSDLDemo {
    /**
     * Auther sun
     * DATE 2022/4/29 16:18
     * VERSION 1.0
     */

    public static void main(String[] args) throws IOException {

        String fileName = "user.graphqls";
        String fileContent = IOUtils.toString(GraphQLSchema.class.getClassLoader().getResource(fileName),"UTF-8");

        TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(fileContent);
        RuntimeWiring wiring = RuntimeWiring.newRuntimeWiring()
                .type("UserQuery", builder -> builder.dataFetcher("user", environment ->{
                    Long id = environment.getArgument("id");
                    return new User(id, "张三"+id, 20+id.intValue());
                }))
                .build();

        SchemaGenerator graphQLSchema = new SchemaGenerator();
        GraphQLSchema schema = graphQLSchema.makeExecutableSchema(typeDefinitionRegistry, wiring);

        GraphQL graphQL = GraphQL.newGraphQL(schema).build();

        String query = "{user(id:100){id,name,age}}";
        ExecutionResult result = graphQL.execute(query);

        //标准反馈
        System.out.println(result.toSpecification());
        System.out.println(result.getData().toString());
    }
}
